package com.lyw.forum.controller;

import com.lyw.forum.common.enums.ResultCode;
import com.lyw.forum.common.exception.ApplicationException;
import com.lyw.forum.pojo.response.AppResult;
import com.lyw.forum.pojo.response.BoardSelectResponse;
import com.lyw.forum.service.IBoardService;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lyw
 */

@Slf4j
@RestController
@RequestMapping("/board")
public class BoardController {

    @Resource
    private IBoardService boardService;

    @Value("${forum.index.board-num}")
    private Integer indexBoardNum;

    @RequestMapping("/toList")
    public AppResult<List<BoardSelectResponse>> toList() {
        //打印日志
        log.info("首页板块的个数为: " + indexBoardNum);

        //调用service查询结果
        List<BoardSelectResponse> boardSelectResponses = boardService.selectByNum(indexBoardNum);

        //判断是否为空
        if(boardSelectResponses == null) {
            boardSelectResponses = new ArrayList<>();
        }

        //但会结果
        return AppResult.success(boardSelectResponses);
    }

    //通过ID查询板块信息
    @RequestMapping("/getById")
    public AppResult<BoardSelectResponse> getById(@NotNull(message = "板块id不能为空") Integer id) {
        //调用service查询结果
        BoardSelectResponse boardSelectResponse = boardService.selectById(id);

        //对查询结果进行校验
        if(boardSelectResponse == null || boardSelectResponse.getDeleteState() == 1) {
            //打印日志
            log.error(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        //返回结果
        return AppResult.success(boardSelectResponse);
    }
}
